//
//  TodayListSubViewController.m
//  UI_A段项目_iDaily Watch
//
//  Created by 刘旭 on 14-10-16.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "TodayListSubViewController.h"

//list页面链接页
@interface TodayListSubViewController ()<UITableViewDataSource, UITableViewDelegate>

@end

@implementation TodayListSubViewController
- (void)dealloc
{
    [_dataArrOne release];
    [_dataArrTwo release];
    [_dataArrThree release];
    [_arr release];
    [super dealloc];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.dataArrOne = [NSMutableArray array];//scrollView 数组
        self.arr = [NSMutableArray array];//接受ablum数据的数组
        self.dataArrTwo = [NSMutableArray array];//CellTwo数组
       
    }
    return self;
}
- (void)viewDidLoad {
    [self getData];
    [super viewDidLoad];
    [self tableView1];
    self.tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"1.png"]];
    
    // Do any additional setup after loading the view.
}
#pragma mark -
#pragma mark webView JSP自适应
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
//    NSString *meta = [NSString stringWithFormat:@"document.getElementsByName(\"viewport\")[0].content = \"width=%f, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"", webView.frame.size.width];
//    [webView stringByEvaluatingJavaScriptFromString:meta];
//    [webView stringByEvaluatingJavaScriptFromString:
//     @"var tagHead =document.documentElement.firstChild;"
//     "var tagMeta = document.createElement(\"meta\");"
//     "tagMeta.setAttribute(\"http-equiv\", \"Content-Type\");"
//     "tagMeta.setAttribute(\"content\", \"text/html; charset=utf-8\");"
//     "var tagHeadAdd = tagHead.appendChild(tagMeta);"];
//    [webView stringByEvaluatingJavaScriptFromString:
//     @"var tagHead =document.documentElement.firstChild;"
//     "var tagStyle = document.createElement(\"style\");"
//     "tagStyle.setAttribute(\"type\", \"text/css\");"
//     "tagStyle.appendChild(document.createTextNode(\"BODY{padding: 20pt 15pt}\"));"
//     "var tagHeadAdd = tagHead.appendChild(tagStyle);"];
//    [webView stringByEvaluatingJavaScriptFromString:
//     @"var script = document.createElement('script');"
//     "script.type = 'text/javascript';"
//     "script.text = \"function ResizeImages() { "
//     "var myimg,oldwidth;"
//     "var maxwidth=320;"
//     "for(i=0;i <document.images.length;i++){"
//     "myimg = document.images;"
//     "if(myimg.width > maxwidth){"
//     "oldwidth = myimg.width;"
//     "myimg.width = maxwidth;"
//     "myimg.height = myimg.height * (maxwidth/oldwidth);"
//     "}"
//     "}"
//     "}\";"
//     "document.getElementsByTagName('head')[0].appendChild(script);"];
//    [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];

    webView.frame = CGRectMake(0, Height * 200, Width * 320,   webView.scrollView.contentSize.height);
    
    [_tableView reloadData];
    
    
    
}
#pragma mark -
#pragma mark 获取数据
- (void)getData
{
    AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
    [manager1 GET:@"http://watch-cdn.idailywatch.com/api/list/cover/zh-hans?page=1&ver=iphone&app_ver=9" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        for (NSMutableArray *arr2 in responseObject) {
            TodayListSubCellTwo *sub1 = [[TodayListSubCellTwo alloc]init];
            arr2 = [NSMutableArray arrayWithArray:responseObject];
//            [arr2 removeObjectAtIndex:4];
            //上一页传进来的count   取文字栏
            sub1.title = [arr2[_count - 1000] objectForKey:@"title"];
            sub1.source = [arr2[_count - 1000] objectForKey:@"source"];
            sub1.pubdate = [arr2[_count - 1000] objectForKey:@"pubdate"];
            sub1.author = [arr2[_count - 1000] objectForKey:@"author"];
            [_dataArrTwo addObject:sub1];
            [_tableView reloadData];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    }];
    
    //获取webView内容
    self.dataArrThree = [NSMutableArray array];
    AFHTTPRequestOperationManager *manager2 = [AFHTTPRequestOperationManager manager];
    [manager2 GET:@"http://watch-cdn.idailywatch.com/api/list/cover/zh-hans?page=1&ver=iphone&app_ver=9" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
       
        for (NSMutableArray *arr2 in responseObject) {
            TodayListSubCellThree *sub2 = [[TodayListSubCellThree alloc]init];
            arr2 = [NSMutableArray arrayWithArray:responseObject];
//            [arr2 removeObjectAtIndex:4];

            sub2.content = [arr2[_count - 1000] objectForKey:@"content"];
            [_dataArrThree addObject:sub2];
            [_tableView reloadData];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];

   
}
#pragma mark -
#pragma mark tableView
- (void)tableView1
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, Width * 320, Height * (568))];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;//不显示CELL条
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_tableView];
    //右上角按钮
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    button1.frame = CGRectMake(0, 0, Width * 30, Height * 30);
    [button1 setBackgroundImage:[UIImage imageNamed:@"ListShare2.png"] forState:UIControlStateNormal];
    [button1 setBackgroundImage:[UIImage imageNamed:@"ListShare1.png"] forState:UIControlStateHighlighted];
    [button1 addTarget:self action:@selector(shareAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item1 = [[UIBarButtonItem alloc]initWithCustomView:button1];
    self.navigationItem.rightBarButtonItem = item1;
    [item1 release];
    //左上角按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(0, 0, Width * 60, Height * 30);
//    [button setBackgroundImage:[UIImage imageNamed:@"TodayList返回1"] forState:UIControlStateNormal];
//    [button setBackgroundImage:[UIImage imageNamed:@"TodayList返回2"] forState:UIControlStateHighlighted];
    [button setTitle:@"返回" forState:UIControlStateNormal];
    [button setTintColor:[UIColor whiteColor]];
    button.titleLabel.font = [UIFont systemFontOfSize:14];
    [button addTarget:self action:@selector(buttonActionSecond) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = item;
    [item release];
}
#pragma mark - 
#pragma mark 回手势侧滑页面
- (void)buttonActionSecond
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 
#pragma mark 分享触发事件
- (void)shareAction
{
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"share"  ofType:@"jpg"];
    
    
    //构造分享内容
    id<ISSContent> publishContent = [ShareSDK content:[NSString stringWithFormat:@"%@\n看到一个好宝贝,分享给大家😊", [_dataArrTwo[_count -1000]title]]
                                       defaultContent:@"默认分享内容，没内容时显示"
                                                image:[ShareSDK imageWithPath:imagePath]
                                                title:@"ShareSDK"
                                                  url:@"http://www.sharesdk.cn"
                                          description:@"这是一条测试信息"
                                            mediaType:SSPublishContentMediaTypeNews];
    
    [ShareSDK showShareActionSheet:nil
                         shareList:nil
                           content:publishContent
                     statusBarTips:YES
                       authOptions:nil
                      shareOptions: nil
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                if (state == SSResponseStateSuccess)
                                {
                                    NSLog(@"分享成功");
                                }
                                else if (state == SSResponseStateFail)
                                {
                                    NSLog(NSLocalizedString(@"TEXT_SHARE_FAI", @"发布失败!error code == %d, error code == %@"), [error errorCode], [error errorDescription]);
                                }
                            }];
}
#pragma mark -
#pragma mark cell行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return Height * 110;
    }
    else if(indexPath.row == 1)
    {
        return Height *  85;
    }
    else
        return   _webView.scrollView.contentSize.height + 100;
}
#pragma mark - 
#pragma mark cell数量
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_arr.count == 0 || _dataArrTwo.count == 0 || _dataArrThree.count == 0) {
        return 0;
    }
    return 3;
}
#pragma mark - 
#pragma mark UITableViewCell重用
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        static NSString *identifier = @"cellOne";
        TodayListSubCellOneTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[TodayListSubCellOneTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
            [cell getCount:_countList];//接收上一页面数组里传来的个数 创建button
        }
        cell.selectionStyle = NO;
        for (int i = 0; i < _countList; i++) {
            cell.button = (UIButton *)[cell viewWithTag:i + 1];
            [cell.button setBackgroundImageWithURL:[NSURL URLWithString:[_arr[(indexPath.row) + i]cover_thumb1]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"1.png"]];
            [cell.button addTarget:self action:@selector(buttonListSmall:) forControlEvents:UIControlEventTouchUpInside];

        }
        return cell;
    }
    //文字栏赋值
    else if(indexPath.row == 1){
        static NSString *identifier = @"cellTwo";
        TodayListSubCellTwoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[TodayListSubCellTwoTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        }
        cell.selectionStyle = NO;
        cell.label1.text = [_dataArrTwo[(indexPath.row - 1)]source];
        cell.label2.text = [_dataArrTwo[(indexPath.row - 1)]title];
        cell.label3.text = [_dataArrTwo[(indexPath.row - 1)]author];
        cell.label4.text = [_dataArrTwo[(indexPath.row - 1)]pubdate];
        return cell;
    }
    //webView赋值
    else if(indexPath.row == 2)
    {
        static NSString * identifier = @"cell3";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
            self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(0 ,Height * 200,Width * 320, Height * 200)];
            NSString *str = [NSString stringWithFormat:@"%@", [_dataArrThree[(indexPath.row - 2)]content]];
            _webView.delegate = self;
            _webView.scrollView.scrollEnabled = NO;
            [_webView loadHTMLString:str baseURL:nil];
            [self.tableView addSubview:_webView];
        }
        return cell;
    }
  
        return nil;
}
#pragma mark -
#pragma mark 去ListSmall页面
- (void)buttonListSmall:(UIButton *)sender
{
    TodayListSmallViewController *vc = [[TodayListSmallViewController alloc]init];
    vc.array = self.arr;//上一页album传来的数据给ListSmall
    vc.count = sender.tag;//下一页接收本页传来的tag 获取cover_landscape图片
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
